<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/11/7
 * Time: 9:31
 */
namespace app\v1\model;

use think\Db;

class Userpay extends \think\Model
{
    private $tableName = "userPay";

    public function addUserpay($data)
    {
        if (!empty($data['merchantId']) && !empty($data['userId']) && !empty($data['amount']) && !empty($data['orderId'])) {
            $data['createTime'] = time();
            $data['payNumber'] = "";
            $data['orderStatus'] = "0";
            $data['remarks'] = "";
            $data['payTime']="";
            $data['isDelete']="0";//伪删除
            return Db::name($this->tableName)->insertGetId($data);
        } else {
            return 404;//字段填写不完整
        }
    }

    public function optionsUserpay($data)
    {
        $total = config("total");
        $data['page']=empty($data['page']) ? 1 : $data['page'];
        if(empty($data['orderStatus'])){
            return  Db::name($this->tableName)->limit(($data['page']-1)*$total,$total)->select();
        }else{
            return  Db::name($this->tableName)->where("orderStatus",$data['orderStatus'])->limit(($data['page']-1)*$total,$total)->select();
        }
    }

    public function delUserpay($id)
    {
        return Db::name($this->tableName)->where("_id", $id)->delete();
    }

    public function updateUserpay($data)
    {
        if($data['orderStatus']==2) {
            //退款给用户
            Db::name($this->tableName)->where("_id",$data['_id'])->update(['orderStatus'=>2]);
        }else if($data['orderStatus']==1){
            $userPayInfo=$this->getUserpayById($data['_id']);
            $arr=["status"=>1];//更改为已支付
            $orderState = json_decode(model("Curlfunction")->getApiByName(config("orderDomain") . "/orders/" . $userPayInfo['orderId'] , "PUT", $arr));
            if($orderState==200) {
                Db::name($this->tableName)->update($data);
            }
            return $orderState;
        }else{
            return Db::name($this->tableName)->update($data);
        }
    }

    public function putUserpay($data)
    {

    }

    public function getUserpayById($id)
    {
        return Db::name($this->tableName)->where("_id", $id)->find();
    }
    /*
     * 根据支付订单原路返回金额给用户
     * @param
     *
     * */
    public function returnMoneyToUser($data){
        Db::startTrans();
        try {
            //删除渠道商所有的子渠道信
            $userPayArr=$this->getUserpayById($data['_id']);//查询订单信息
            //Db::name("user")->where("open_id", $userPayArr['open_id'])->setInc("amount",$userPayArr['amount']);;//退回余额给用户
            model("paypublic")->payWeiXinTX($userPayArr);
            $res=true;
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            $res=false;
            Db::rollback();
        }
    }
}